//
//  HLUserAccountViewModel.m
//  weibo-OC
//
//  Created by 黄力 on 15/12/15.
//  Copyright © 2015年 HLTest. All rights reserved.
//

#import "HLUserAccountViewModel.h"
#import <AFNetworking.h>
#import "HLUserAccount.h"
#import "HLNetworking.h"

@interface HLUserAccountViewModel ()

@property (nonatomic,strong) HLUserAccount *userAccount;

@end

@implementation HLUserAccountViewModel

//返回用户的登录状态
+ (BOOL)getUserLogin {
    //根据取出的数据是否为空来判断用户的状态
    return ([HLUserAccount getUserAccount] != nil);
}
//用户头像
+ (NSString *)getUserImage {
    return [HLUserAccount getUserAccount].avatar_large;
}
//用户昵称
+ (NSString *)getUserName {
    return [HLUserAccount getUserAccount].name;
}
//用户token
+ (NSString *)getUserToken {
    return [HLUserAccount getUserAccount].access_token;
}

//获取用户的token
+ (void)loadTokenWithCode:(NSString *)code withFinshBlock:(FinshBlock)finshBlock{
    //设置要传递的参数
    NSDictionary *parameters = @{@"client_id":OAuthAppKey,
                                 @"client_secret":OAuthAppSecret,
                                 @"grant_type":@"authorization_code",
                                 @"code":code,
                                 @"redirect_uri":OAuthAppRedirect};
    
    
    //发送网络请求
    [[HLNetworking sharedNetworing] sendHTTPRequestWithHTTPMethod:@"POST" withUrlStr:@"oauth2/access_token" withParameters:parameters withFinshedBlock:^(id resultData, NSError *error) {
        //判断是否成功
        if (error == nil) {
            //根据获取的token来请求用户的信息
            [self loadUserInfoWithTokenDic:resultData withFinshBlock:finshBlock];
        }else {
            //失败的回调
            finshBlock(NO);
        }
    }];
    
}

//获取用户信息
+ (void)loadUserInfoWithTokenDic:(NSDictionary *)dic withFinshBlock:(FinshBlock)finshBlock{
    //创建用户信息模型对象
    HLUserAccount *userAccount = [HLUserAccount userAccountWithDictionary:dic];
    //获取用户的token
    NSString *access_token = dic[@"access_token"];
    NSString *uid = dic[@"uid"];
    //设置请求参数
    NSDictionary *parameters = @{@"access_token":access_token,@"uid":uid};
    //请求用户信息
    [[HLNetworking sharedNetworing] sendHTTPRequestWithHTTPMethod:@"GET" withUrlStr:@"2/users/show.json" withParameters:parameters withFinshedBlock:^(id resultData, NSError *error) {
        //判断是否成功
        if (error == nil) {
            //获取用户的昵称
            NSString *name = resultData[@"name"];
            //获取用户头像
            NSString *avatar_large = resultData[@"avatar_large"];
            //保存用户信息
            userAccount.name = name;
            userAccount.avatar_large = avatar_large;
            //保存到沙盒
            [userAccount saveUserAccountToSanbox];
            //成功的回调
            finshBlock(YES);
        }else {
            //失败的回调
            finshBlock(NO);
        }
    }];
    
}

@end
